#include "net.h"
#include <QApplication>
#include <QDialog>
#include <QPushButton>
#include <QCheckBox>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <qsizepolicy.h>
#include <qlayout.h>
#include <QLineEdit>
#include <QListWidget>
#include <QMessageBox>

Net::Net(char *v1, char * v2): QDialog(NULL), sok(new QUdpSocket)
{
    if (!sok->bind(QHostAddress(v1), atoi(v2)))
    {
        QMessageBox::information(this, "error", "error");
    }

    QVBoxLayout *vmainlay=new QVBoxLayout();
    QHBoxLayout *h1lay=new QHBoxLayout();
    QHBoxLayout *h2lay=new QHBoxLayout();
    QHBoxLayout *h3lay=new QHBoxLayout();

    vmainlay->addItem(h1lay);
    vmainlay->addItem(h2lay);
    vmainlay->addItem(h3lay);

    QListWidget * w_list= new QListWidget(this);
    h1lay->addWidget(w_list);

    ip=new QLineEdit("192.168.13.21", this);
    h2lay->addWidget(ip);
    h2lay->addItem(new QSpacerItem(20, 20));
    port= new QLineEdit("1205", this);
    h2lay->addWidget(port);


    line=new QLineEdit("Hi there!", this);
    h3lay->addWidget(line);
    h3lay->addItem(new QSpacerItem(20, 20));
    QPushButton *but=new QPushButton("Send", this);
    h3lay->addWidget(but);

    setLayout(vmainlay);

    connect(but, SIGNAL(clicked()), this, SLOT(SendMessage()));
    connect(sok, SIGNAL(readyRead()), this, SLOT(ReadMessage()));
}

void Net::SendMessage()
{
     QByteArray data;
     data.append(line->text());
     sok->writeDatagram(data, QHostAddress(ip->text()), port->text().toInt());

     QString d(data);
     w_list->addItem(d);
}

void Net::ReadMessage()
{
   while (sok->hasPendingDatagrams())
    {
       QByteArray data;
       quint64 maxlen= sok->pendingDatagramSize();
       data.resize(maxlen);
       sok->readDatagram(data.data(), maxlen, 0, 0);

       QString d(data);
       w_list->addItem(d);
   }
}
